/*
 * Copyright 2016-2019 yoara
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *     http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */

package yhao.infra.feature.mail.core.sender;

import org.springframework.beans.factory.InitializingBean;

import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * 邮件发送池
 *
 * @author yoara
 */
public class MailSenderPool implements InitializingBean{
    //工厂路由key
    private String senderKey;
    //单个实体对象Bean配置的
    private List<MailSender> mailSenderList;
    //邮件发送池工厂
    private final static Map<String,MailSenderPool> mailSenderFactory = new HashMap<>();

    public void setSenderKey(String senderKey) {
        this.senderKey = senderKey;
    }

    public void setMailSenderList(List<MailSender> mailSenderList) {
        this.mailSenderList = mailSenderList;
    }

    @Override
    public void afterPropertiesSet(){
        synchronized (mailSenderFactory){
            if(senderKey==null){
                throw new IllegalArgumentException("mail sender [senderKey] cannot be null!");
            }
            if(mailSenderList==null||mailSenderList.size()==0){
                throw new IllegalArgumentException("mail sender:["+senderKey+"] cannot be empty!");
            }
            if(mailSenderFactory.get(senderKey)!=null){
                throw new IllegalArgumentException("mail sender:["+senderKey+"] has been Initialized!");
            }
            mailSenderFactory.put(senderKey,this);
        }
    }

    public static MailSenderPool getMailSenderList(String senderKey) {
        MailSenderPool pool = mailSenderFactory.get(senderKey);
        if(pool==null){
            throw new RuntimeException("no mail sender found");
        }
        return pool;
    }

    public List<MailSender> getMailSenderList() {
        return mailSenderList;
    }
}
